package com.qf.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// jdk动态代理
public class JDKProxy implements InvocationHandler {

    private Object obj;   // userServiceImpl,goodServiceImpl

    public JDKProxy(Object obj) {
        // 传入被代理对象
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("执行方法:" + method.getName());
        System.out.println("开启事务");
        try {
            Object result = method.invoke(obj, args);
            System.out.println("提交事务");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回滚事务");
            return null;
        }
    }


    public Object getProxyInstance(){
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
    }
}
